#!/usr/bin/env node
/**
 * 对话记录系统 MCP 服务器
 */
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import {
    CallToolRequestSchema,
    ErrorCode,
    ListResourcesRequestSchema,
    ListResourceTemplatesRequestSchema,
    ListToolsRequestSchema,
    McpError,
    ReadResourceRequestSchema,
} from '@modelcontextprotocol/sdk/types.js';

import {
    initDatabase,
    addConversation,
    updateConversation,
    deleteConversation,
    getConversation,
    searchConversations,
    getConversationStats
} from './database.js';
import { SearchParams, AddConversationParams, UpdateConversationParams } from './types.js';

class ConversationRecorderServer {
    private server: Server;

    constructor() {
        this.server = new Server(
            {
                name: 'conversation-recorder',
                version: '0.1.0',
            },
            {
                capabilities: {
                    resources: {},
                    tools: {},
                },
            }
        );

        this.setupResourceHandlers();
        this.setupToolHandlers();

        // 错误处理
        this.server.onerror = (error) => console.error('[MCP Error]', error);
        process.on('SIGINT', async () => {
            await this.server.close();
            process.exit(0);
        });
    }

    private setupResourceHandlers() {
        // 列出可用资源
        this.server.setRequestHandler(ListResourcesRequestSchema, async () => ({
            resources: [
                {
                    uri: 'conversation://stats',
                    name: '对话统计信息',
                    mimeType: 'application/json',
                    description: '获取对话记录的统计信息，包括总数、状态分布、最近对话和热门关键词',
                },
            ],
        }));

        // 定义资源模板
        this.server.setRequestHandler(
            ListResourceTemplatesRequestSchema,
            async () => ({
                resourceTemplates: [
                    {
                        uriTemplate: 'conversation://{id}',
                        name: '对话记录',
                        mimeType: 'application/json',
                        description: '获取指定ID的对话记录详细信息',
                    },
                ],
            })
        );

        // 读取资源
        this.server.setRequestHandler(
            ReadResourceRequestSchema,
            async (request) => {
                if (request.params.uri === 'conversation://stats') {
                    const result = await getConversationStats();
                    if (!result.success) {
                        throw new McpError(ErrorCode.InternalError, result.message);
                    }
                    return {
                        contents: [
                            {
                                uri: request.params.uri,
                                mimeType: 'application/json',
                                text: JSON.stringify(result.data, null, 2),
                            },
                        ],
                    };
                }

                const match = request.params.uri.match(/^conversation:\/\/([^/]+)$/);
                if (!match) {
                    throw new McpError(
                        ErrorCode.InvalidRequest,
                        `无效的URI格式: ${request.params.uri}`
                    );
                }

                const id = decodeURIComponent(match[1]);
                const result = await getConversation(id);

                if (!result.success) {
                    throw new McpError(ErrorCode.NotFound, result.message);
                }

                return {
                    contents: [
                        {
                            uri: request.params.uri,
                            mimeType: 'application/json',
                            text: JSON.stringify(result.data, null, 2),
                        },
                    ],
                };
            }
        );
    }

    private setupToolHandlers() {
        this.server.setRequestHandler(ListToolsRequestSchema, async () => ({
            tools: [
                {
                    name: 'add_conversation',
                    description: '添加新的对话记录',
                    inputSchema: {
                        type: 'object',
                        properties: {
                            topic: { type: 'string', description: '对话主题' },
                            keywords: {
                                type: 'array',
                                items: { type: 'string' },
                                description: '关键词列表'
                            },
                            summary: { type: 'string', description: '对话摘要' },
                            actions: {
                                type: 'array',
                                items: { type: 'string' },
                                description: '行动项列表'
                            },
                            files: {
                                type: 'array',
                                items: { type: 'string' },
                                description: '相关文件路径列表'
                            },
                            status: { type: 'string', description: '对话状态' },
                            content: { type: 'string', description: '对话详细内容' }
                        },
                        required: ['topic', 'keywords', 'summary', 'status']
                    }
                },
                {
                    name: 'update_conversation',
                    description: '更新现有的对话记录',
                    inputSchema: {
                        type: 'object',
                        properties: {
                            id: { type: 'string', description: '对话ID' },
                            topic: { type: 'string', description: '对话主题' },
                            keywords: {
                                type: 'array',
                                items: { type: 'string' },
                                description: '关键词列表'
                            },
                            summary: { type: 'string', description: '对话摘要' },
                            actions: {
                                type: 'array',
                                items: { type: 'string' },
                                description: '行动项列表'
                            },
                            files: {
                                type: 'array',
                                items: { type: 'string' },
                                description: '相关文件路径列表'
                            },
                            status: { type: 'string', description: '对话状态' },
                            content: { type: 'string', description: '对话详细内容' }
                        },
                        required: ['id']
                    }
                },
                {
                    name: 'delete_conversation',
                    description: '删除对话记录',
                    inputSchema: {
                        type: 'object',
                        properties: {
                            id: { type: 'string', description: '对话ID' }
                        },
                        required: ['id']
                    }
                },
                {
                    name: 'search_conversations',
                    description: '搜索对话记录',
                    inputSchema: {
                        type: 'object',
                        properties: {
                            id: { type: 'string', description: '按ID搜索' },
                            topic: { type: 'string', description: '按主题搜索' },
                            keywords: {
                                type: 'array',
                                items: { type: 'string' },
                                description: '按关键词搜索'
                            },
                            status: { type: 'string', description: '按状态搜索' },
                            date: { type: 'string', description: '按日期搜索 (YYYY-MM-DD)' },
                            limit: { type: 'number', description: '结果数量限制' }
                        }
                    }
                }
            ],
        }));

        this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
            switch (request.params.name) {
                case 'add_conversation': {
                    const params = request.params.arguments as AddConversationParams;
                    const result = await addConversation(params);
                    return this.formatToolResponse(result);
                }

                case 'update_conversation': {
                    const params = request.params.arguments as UpdateConversationParams;
                    const result = await updateConversation(params);
                    return this.formatToolResponse(result);
                }

                case 'delete_conversation': {
                    const { id } = request.params.arguments as { id: string };
                    const result = await deleteConversation(id);
                    return this.formatToolResponse(result);
                }

                case 'search_conversations': {
                    const params = request.params.arguments as SearchParams;
                    const result = await searchConversations(params);
                    return this.formatToolResponse(result);
                }

                default:
                    throw new McpError(
                        ErrorCode.MethodNotFound,
                        `未知的工具: ${request.params.name}`
                    );
            }
        });
    }

    private formatToolResponse(result: { success: boolean; message?: string; data?: any }) {
        if (!result.success) {
            return {
                content: [
                    {
                        type: 'text',
                        text: result.message || '操作失败',
                    },
                ],
                isError: true,
            };
        }

        return {
            content: [
                {
                    type: 'text',
                    text: JSON.stringify(result.data || { message: result.message }, null, 2),
                },
            ],
        };
    }

    async run() {
        // 初始化数据库
        const dbResult = await initDatabase();
        if (!dbResult.success) {
            console.error(dbResult.message);
            process.exit(1);
        }

        // 启动服务器
        const transport = new StdioServerTransport();
        await this.server.connect(transport);
        console.error('对话记录系统 MCP 服务器已启动');
    }
}

// 启动服务器
const server = new ConversationRecorderServer();
server.run().catch(console.error);